<?php

namespace app\admin\model\weixin;

use addons\weixin\library\WechatTemplateService;
use think\Model;
use think\Cache;

class Template extends Model
{
    // 表名
    protected $name = 'weixin_template';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'add_time';
    protected $updateTime = false;
    protected $deleteTime = false;

    /**
     * @notes 得到行业
     * @author 兴
     * @date 2022/10/31 19:41
     */
    public function getIndustry()
    {
        $industry = Cache::tag('_system_wechat')->remember('_wechat_industry', function () {
            try {
                $cache = WechatTemplateService::getIndustry();
                if (!$cache) {
                    return [];
                }
                Cache::tag('_system_wechat', ['_wechat_industry']);
                return $cache;
            } catch (\Exception $e) {
                return $e->getMessage();
            }
        }, 0) ?: [];
        !is_array($industry) && $industry = [];
        return $industry;
    }

    /**
     * @notes 同步模板
     * @author 兴
     * @date 2022/10/31 19:42
     */
    public function getTemplates()
    {
        //得到模板列表并检测入库
        $templates = Cache::tag('_system_wechat')->remember('_wechat_templates', function () {
            try {
                $cache = WechatTemplateService::getPrivateTemplates();
                if (!$cache) {
                    return [];
                }
                Cache::tag('_system_wechat', ['_wechat_templates']);
                return $cache;
            } catch (\Exception $e) {
                return $e->getMessage();
            }
        }, 0) ?: [];
        !is_array($templates) && $templates = [];

        if (isset($templates['template_list']) && !empty($templates['template_list'])) {
            foreach ($templates['template_list'] as $key => $val) {
                if ($this->where(['tempid'=>$val['template_id']])->count()) {
                    continue;
                }
                $this->insert([
                    'tempkey' => 'OPENTM' . time() . $key,
                    'name' => $val['title'],
                    'content' => $val['content'],
                    'tempid' => $val['template_id'],
                    'add_time' => time(),
                    'status' => 1,
                ]);
            }
        }
    }
}
